package com.accp.dao.impl;

import com.accp.dao.DoctorDao;
import com.accp.pojo.Doctor;
import org.hibernate.HibernateException;
import org.hibernate.Query;

import java.util.ArrayList;
import java.util.List;

public class DoctorDaoImpl extends BaseDaoImpl implements DoctorDao {
    /**
     * 查找所有医生（分页多条件）
     * @param doctor
     * @return
     */
    public List<Doctor>  selectByPage(String className, int pageNo, int pageSize,Doctor doctor){
        List<Doctor> list = new ArrayList<Doctor>();
        String hql = "from "+className; //查询所有医生
        if(doctor.getName()!=null&&doctor.getName()!=""){
             hql = "from "+className+" where name like '%"+doctor.getName()+"%'"; //根据条件查询所有医生
        }
        Query query = this.getSession().createQuery(hql);
        query.setFirstResult((pageNo - 1) * pageSize);//每页显示的第一条记录
        query.setMaxResults(pageSize);//每页显示的记录数
        return query.list();
    }

    /**
     * 添加医生
     * @param doctor
     * @return
     */
    public boolean add(Doctor doctor){
        boolean flag = false;
        try{
            getSession().save(doctor);
            flag = true;
        }catch(HibernateException e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 通过ID查找用户
     */
    @Override
    public Doctor findByDoctorId(Integer id) {
        Doctor doctor = (Doctor) getSession().get(Doctor.class,id);
        return doctor;
    }

    /**
     * 修改医生信息
     */
    @Override
    public boolean update(Doctor doctor) {
        boolean flag = false;
        try{
            getSession().update(doctor);
            flag = true;
        }catch(HibernateException e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除医生
     * @param doctor
     * @return
     */
    public boolean deleteDoctor(Doctor doctor){
        boolean flag = false;
        try{
            getSession().delete(doctor);
            flag = true;
        }catch(HibernateException e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 分页查看，获取总记录数。
     * @param className
     * @return
     */
    public int totalPage(String className,String name){
        String hql = "select count(*) from "+className;
        if(name!=null&&name!=""){
            hql = "select count(*) from "+className+" where name like '%"+name+"%'"; //根据条件查询所有医生
        }
        Query query = this.getSession().createQuery(hql);
        int total = Integer.parseInt(query.list().get(0).toString());
        return total;
    }


}
